/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.wsapi.core.auth;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

/**
 *
 * 脱裤子放屁的功能
 *
 * @author yangyan <y.os@qq.com>
 */
public class CaptchaFormAuthenticationFilter extends FormAuthenticationFilter {

    private String captchaParam = "captcha";

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        return new UsernamePasswordCaptchaToken(getCaptcha(request), getUsername(request), getPassword(request));
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        if (isLoginRequest(request, response)) {
            //检查验证码是否正确
            Object captcha = SecurityUtils.getSubject().getSession().getAttribute(captchaParam);
            SecurityUtils.getSubject().getSession().removeAttribute(captchaParam);
            if (captcha != null) {
                if (!captcha.equals(getCaptcha(request))) {
                    throw CaptchaNoMatchException.SINGLETON;
                }
            }
        }
        return super.onAccessDenied(request, response, mappedValue);
    }

    public void setCaptchaParam(String captchaParam) {
        this.captchaParam = captchaParam;
    }

    public String getCaptchaParam() {
        return captchaParam;
    }

    private String getCaptcha(ServletRequest request) {
        return WebUtils.getCleanParam(request, getCaptchaParam());
    }

//    public void init(FilterConfig filterConfig) throws ServletException {
//        ajaxHeaderParam = filterConfig.getInitParameter("ajaxHeaderParam");
//        if (ajaxHeaderParam == null) {
//            //extjs used default ajax header
//            ajaxHeaderParam = "X-Requested-With";
//        }
//    }
//
//
//    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//
//        String header = ((HttpServletRequest) request).getHeader(ajaxHeaderParam);
//
//        if ("XMLHttpRequest".equals(header)) {
//            if (!SecurityUtils.getSubject().isAuthenticated()) {
//                response.getWriter().print("{success:false,msg:'登录超时'}");
//                return;
//            }
//        }
//
//        chain.doFilter(request, response);
//
//    }
}
